package service

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"lab.com/helper"
	"lab.com/model"
)

func GetUserDetial(c *gin.Context) {
	identity := c.Query("identity")
	if identity == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"mag":  "用户唯一标识不能为空",
		})
		return

	}
	data := new(model.Users)
	err := model.DB.Where("identity = ?", identity).Find(&data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"mag":  "Get Users Detail By Tdentity:" + identity + "Error:" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": data,
	})

}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"mag":  "必填信息为空",
		})
		return
	}

	password = helper.GetMd5(password)

	data := new(model.Users)
	err := model.DB.Where("name = ? AND password = ?", username, password).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"mag":  "用户名或密码错误",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"mag":  "Get Users Error:" + err.Error(),
		})
		return
	}

	token, err := helper.GenerateToken(data.Identity, data.Name)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"mag":  "GenerateToken Error:" + err.Error(),
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"code": -1,
		"data": map[string]interface{}{
			"token": token,
		},
	})
}
